"""Sphinx configuration"""

# pylint: disable=import-error, invalid-name

#
# Modules
#

import os
import pathlib
import re
import sys

from sphinx.application import Sphinx
from sphinx import addnodes

sys.path.append(os.path.realpath(pathlib.Path(__file__).parents[1]))
from sievemgr import __author__, __copyright__, __version__


#
# Configuration
#

project = 'SieveManager'
release = __version__
version = __version__
# pylint: disable=redefined-builtin
copyright = __copyright__
author = __author__

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosectionlabel',
    'sphinx.ext.autosummary',
    'sphinx.ext.intersphinx',
    'sphinx.ext.mathjax',
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinxext.opengraph',
    'sphinx_copybutton',
    'sphinxcontrib.mermaid',
    'enum_tools.autoenum'
]

exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
language = 'en'

rst_prolog = """
.. include:: links.rst
"""

# More noise than info.
suppress_warnings = ['autosectionlabel.*']
templates_path = ['_templates']

autodoc_class_signature = 'separated'
autodoc_default_options = {
    'members': True,
    'show-inheritance': True,
    'ignore-module-all': True
}
autodoc_member_order = 'groupwise'
autodoc_preserve_defaults = True
autodoc_type_aliases = {
    'Line': 'Line',
    'Word': 'Word',
}

html_title = f'{project} {release}'
html_css_files = [
    'custom.css',
]
html_static_path = ['_static/html/custom.css']
html_theme = 'furo'
html_theme_options = {
    'light_css_variables': {
        'color-api-name': 'var(--color-content-foreground)',
        'color-api-pre-name': 'var(--color-content-foreground)'
    },
    'dark_css_variables': {
        'color-api-name': 'var(--color-content-foreground)',
        'color-api-pre-name': 'var(--color-content-foreground)'
    }
}

man_pages = [
    ('command', 'sievemgr', 'manage remote Sieve scripts', '', 1),
    ('config', 'sieve.cf', 'SieveManager configuration', '', 5)
]

manpages_url = 'https://man.freebsd.org/cgi/' \
               'man.cgi?query={page}&sektion={section}'

mermaid_init_js = """mermaid.initialize({
    startOnLoad: true,
    theme: 'neutral',
    securityLevel: 'loose',
    fontFamily:
        getComputedStyle(document.body).getPropertyValue('--font-stack'),
    flowchart: {
        htmlLabels: true
    }
});"""

ogp_site_url = 'https://odkr.codeberg.page/sievemgr'


#
# Custom object types
#

def parse(_, text, node):
    """Parse SieveManager commands and configuration variables."""
    operators = ('[', ']', '|', '...')
    name, *args = filter(bool, re.split(r'([\b\s\[\]|,@])', text))
    node.children.append(addnodes.desc_sig_name(name, name))
    node.children.extend(
        addnodes.desc_sig_space() if arg.isspace() else
        addnodes.desc_sig_keyword(arg, arg) if arg.isalnum() else
        addnodes.desc_sig_operator(arg, arg) if arg in operators else
        addnodes.desc_sig_literal_string(arg, arg)
            for arg in args
    )
    return name


def setup(app: Sphinx):
    """Add SieveManager command and configuration variable directives."""
    app.add_object_type(
        'confvar',
        'confvar',
        objname='configuration variable',
        indextemplate='pair: %s; configuration variable',
        parse_node=parse
    )

    app.add_object_type(
        'sievecmd',
        'sievecmd',
        objname='SieveManager command',
        indextemplate='pair: %s; SieveManager command',
        parse_node=parse
    )
